package com.sofwin.realm;

import com.sofwin.pojo.SUser;
import com.sofwin.service.SUserService;
import lombok.Data;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class userRealm extends AuthorizingRealm {

    private SUserService userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从身份中获取登录名 favicon.ico
        String userName = principalCollection.getPrimaryPrincipal().toString();
        // 根据用户名查询用户，以获取信息
        SUser user = new SUser();
        user.setLoginAccount(userName);
        user = userService.selectUser(user);
        // 开始授权的相关操作
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(String.valueOf(user.getRoleId())); // ?
        List<String> permissions = userService.selectUserPermission(user.getRoleId());
        info.addStringPermissions(permissions);
        System.out.println("授权。。。。。");
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 强转
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        // 获取用户名、密码
        String username = token.getUsername();
        String pwd = String.valueOf(token.getPassword());
        boolean hasLoginAccount = userService.selectUserByLoginAccount(username);
        if (!hasLoginAccount){
            throw new UnknownAccountException();
        }
        // 手动验证
        SUser user = new SUser();
        user.setLoginAccount(username);
        user.setPwd(pwd);
        boolean isExist = userService.checkLogin(user);
        if (!isExist){
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(username,pwd,"BartRealm");
    }

    public void setUserService(SUserService userService) {
        this.userService = userService;
    }
}
